/*!
 * Friend create.
 * usage:
 * $('.avatar').aywFriend({});
 *
 * Depends:
 *  jquery.ui.widget.js
 */
(function($, undefined) {
	$.widget('ui.aywFriend', {
		options: {
			cardSelector: '.friend_card'
		},
		_create: function() {
			var self = this, posOptions = {
				my: 'left top',
				at: 'left bottom',
				of: $(self.element),
				collision: 'flip'
			}, 
			timeHandler=null,
			data=$(self.element).attr('data');//$(self.options.cardSelector);

			$(self.element).on('mouseenter.'+ self.widgetName, function(e){
				var _self = this;
				clearTimeout(timeHandler);
				if ( $(_self).data('card') ) {
					 $(_self).data('card').stop(true,true).show().position(posOptions).hide().delay(1000).show(300);
				} else {
					timeHandler =setTimeout(function(){
						$.get(U('home/friend/card'), {uid:data}, function(_html){
							if (_html) {
								var pos = posOptions
								var _card = $(_html).appendTo('body').show()
										.position(pos)
										.on('mouseleave.'+ self.widgetName, function(e){
											$(this).hide(300);
											return false;
										}).on('mouseenter.'+ self.widgetName, function(e){
											$(this).stop(true,true).show();
											return false;
										});
								_card.find('.scrollable').aywScrollable({items: '.scrollmask ul', size:5});
								_card.find('.qmenu').aywMenu();
								$(_self).data('card', _card);
								self._initActions(_card);
							}
						});						
					}, 1000);
				}
				return false;
			}).on('mouseleave.'+ self.widgetName, function(e){
				clearTimeout(timeHandler);
				$(self.options.cardSelector).stop(true,true).delay(500).hide(300);
				return false;
			});

			$(document).bind('click', function(evt) {
				if ($(evt.target).closest('.friend_card').length) {
					return true;
				} else {
					$(self.options.cardSelector).hide();
				}
			});					
		},
	
		_initActions: function(element) {
			var self = this;
			// add friend 
			$('.friend_32', element).click(function(){
				var _href = $(this).attr('href');
				var _self = this;
				$.get(_href, function(data) {
					if (data == '0') {
						ui.error('添加好好友失败');
					} else {
						ui.success('添加好友成功');
						/*$(self.element).closest('li').appendTo($('.friend_know .friends'));
						$(_self).remove();*/
						location.reload();
					}
				});
				return false;
			});
			
			// delete friend
			$('.delete_32', element).click(function(){
				var _href = $(this).attr('href');
				var _self = this;
				$.get(_href, function(data) {
					if (data == '0') {
						ui.error('删除好好友失败');
					} else {
						ui.success('删除好友成功');
						/*$(self.element).closest('li').appendTo($('.friend_know .friends'));
						$(_self).remove();*/
						location.reload();
					}
				});
				return false;
			});
				
			
		}
	});
})(jQuery);
